package com.hwadee.backend.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwadee.backend.entity.Authorize;
import com.hwadee.backend.entity.Record;
import com.hwadee.backend.entity.UserRecord;
import com.hwadee.backend.entity.user.User;
import com.hwadee.backend.mapper.AuthorizeMapper;
import com.hwadee.backend.mapper.RecordMapper;
import com.hwadee.backend.mapper.UserRecordMapper;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Service
public class AuthorizeService extends ServiceImpl<AuthorizeMapper, Authorize> {
    private static final Logger log = LoggerFactory.getLogger(AuthorizeService.class);

    @Autowired
    private AuthorizeMapper authorizeMapper;

    @Autowired
    private UserRecordMapper userRecordMapper;

    @Autowired
    private RecordMapper recordMapper;

    @Autowired
    private UserService userService;

    public int createAuthorizationRequest(int applicant, int response) {
        Authorize authorize = new Authorize();
        authorize.setApplicant(applicant);
        authorize.setResponse(response);
        authorize.setStatus("pending");
        authorize.setCreateTime(LocalDateTime.now());
        authorize.setUpdateTime(LocalDateTime.now());
        return authorizeMapper.insert(authorize);
    }

    public String getAuthorizationStatus(int applicant, int response) {
        System.out.println("在authorize中收到的applicant:"+applicant+",response:"+response);
        Authorize authorize = authorizeMapper.selectByApplicantAndResponse(applicant, response);
        System.out.println(authorize);
        return authorize != null ? authorize.getStatus() : null;
    }

    public int updateAuthorizationResponse(int applicant, int response, String status) {
        Authorize authorize = authorizeMapper.selectByApplicantAndResponse(applicant, response);
        if (authorize != null) {
            authorize.setStatus(status);
            authorize.setUpdateTime(LocalDateTime.now());
            return authorizeMapper.updateById(authorize);
        }
        return 0;
    }

    /**
     * 根据授权ID获取授权详情
     */
    public Authorize getAuthorizationById(Integer authorizationId) {
        log.info("获取授权详情，授权ID: " + authorizationId);
        return authorizeMapper.selectById(authorizationId);
    }

    /**
     * 获取权限设置
     */
    public Map<String, String> getPermissionSettings(Integer authorizationId) {
        log.info("获取权限设置，授权ID: {}", authorizationId);
        Authorize authorize = authorizeMapper.selectById(authorizationId);
        if (authorize == null) {
            log.warn("授权记录不存在，授权ID: {}", authorizationId);
            return new HashMap<>();
        }

        Map<String, String> permissions = new HashMap<>();
        permissions.put("look", authorize.getLook());
        permissions.put("delete", authorize.getDelete());
        permissions.put("update", authorize.getUpdate());
        return permissions;
    }

    /**
     * 更新权限设置
     */
    public void updatePermissionSettings(Integer authorizationId, Map<String, String> permissions) {
        log.info("更新权限设置，授权ID: {}, 权限数据: {}", authorizationId, permissions);
        Authorize authorize = authorizeMapper.selectById(authorizationId);
        if (authorize == null) {
            log.error("更新权限失败，授权记录不存在，授权ID: {}", authorizationId);
            throw new RuntimeException("授权记录不存在");
        }

        authorize.setLook(permissions.getOrDefault("look", ""));
        authorize.setDelete(permissions.getOrDefault("delete", ""));
        authorize.setUpdate(permissions.getOrDefault("update", ""));
        authorize.setUpdateTime(LocalDateTime.now());
        authorizeMapper.updateById(authorize);
        log.info("权限设置更新成功，授权ID: {}", authorizationId);
    }

    /**
     * 根据用户ID获取授权列表
     */
    public List<Map<String, Object>> getAuthorizationsByUserId(Integer userId) {
        System.out.println("查询用户ID: " + userId + " 的授权列表");
        QueryWrapper<Authorize> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("response", userId)
                .eq("status", "approved");
        // 新增调试日志：打印完整查询条件
        log.info("查询条件 - response: {}, status: approved", userId);
        List<Authorize> authorizations = authorizeMapper.selectList(queryWrapper);
        log.info("查询到的授权记录数量: {}", authorizations.size());
        List<Map<String, Object>> result = new ArrayList<>();
        for (Authorize auth : authorizations) {
            log.info("授权记录详情: {}", auth);
            User doctor = userService.getUserById((long) auth.getApplicant());
            System.out.println("查询到的医生信息: " + doctor);
            Map<String, Object> authInfo = new HashMap<>();
            authInfo.put("authorizationId", auth.getId());
            authInfo.put("doctorId", auth.getApplicant());
            authInfo.put("doctorName", doctor != null ? doctor.getUsername() : "未知医生");
            authInfo.put("authorizeTime", auth.getCreateTime());
            authInfo.put("look", auth.getLook() != null ? auth.getLook() : "");
            authInfo.put("delete", auth.getDelete() != null ? auth.getDelete() : "");
            authInfo.put("update", auth.getUpdate() != null ? auth.getUpdate() : "");
            log.info("构造的授权信息: {}", authInfo);
            result.add(authInfo);
        }
        return result;
    }

    /**
     * 根据授权ID删除授权记录
     */
    public int deleteAuthorizationById(Integer authorizationId) {
        log.info("尝试删除授权记录，授权ID: {}", authorizationId);
        int rowsDeleted = authorizeMapper.deleteById(authorizationId);
        log.info("删除授权记录结果: {} 行受影响", rowsDeleted);
        return rowsDeleted;
    }

    public List<String> getRecordTypeByAuthorizationId(int authorizationId) {
        // 1. 获取授权详情
        Authorize authorize = authorizeMapper.selectById(authorizationId);
        if (authorize == null) {
            throw new RuntimeException("Authorization not found with id: " + authorizationId);
        }
        // 2. 从授权响应中提取用户ID
        int id = authorize.getResponse();
        log.info("从授权响应中提取的用户ID: " + id);
        // 根据用户ID查询用户记录列表
        List<UserRecord> userRecords = userRecordMapper.selectByUserId(id);
        if (userRecords.isEmpty()) {
            throw new RuntimeException("No records found for user ID: " + id);
        }
        // 4. 查询record表获取recordtype
        List<String> recordTypes = new ArrayList<>();
        for (UserRecord userRecord : userRecords) {
            String recordtype = recordMapper.selectRecordtypeByRecordid(userRecord.getRecordId());
            log.info("从数据库获取的recordtype: {}", recordtype);
            if (recordtype != null) {
                recordTypes.add(recordtype);
            }
        }
        log.info("返回的模块种类{}", recordTypes);
        return recordTypes;
    }

    /**
     * 更新查看权限设置
     */
    public void updateLookPermission(Integer authorizationId, String recordType, boolean look) {
        Authorize authorize = baseMapper.selectById(authorizationId);
        if (authorize == null) {
            throw new RuntimeException("授权记录不存在");
        }

        // 处理查看权限字段(String类型，逗号分隔的recordTypes)
        String lookStr = authorize.getLook();
        Set<String> lookSet = new HashSet<>();
        if (lookStr != null && !lookStr.isEmpty()) {
            lookSet.addAll(Arrays.asList(lookStr.split("\\s*,\\s*")));
        }

        if (look) {
            lookSet.add(recordType);
        } else {
            lookSet.remove(recordType);
        }

        authorize.setLook(String.join(",", lookSet));
        baseMapper.updateById(authorize);
    }

    /**
     * 更新删除权限设置
     */
    public void updateDeletePermission(Integer authorizationId, String recordType, boolean delete) {
        Authorize authorize = baseMapper.selectById(authorizationId);
        if (authorize == null) {
            throw new RuntimeException("授权记录不存在");
        }

        // 处理删除权限字段(String类型，逗号分隔的recordTypes)
        String deleteStr = authorize.getDelete();
        Set<String> deleteSet = new HashSet<>();
        if (deleteStr != null && !deleteStr.isEmpty()) {
            deleteSet.addAll(Arrays.asList(deleteStr.split(",")));
        }

        if (delete) {
            deleteSet.add(recordType);
        } else {
            deleteSet.remove(recordType);
        }

        authorize.setDelete(String.join(",", deleteSet));
        baseMapper.updateById(authorize);
    }

    /**
     * 更新修改权限设置
     */
    public void updateUpdatePermission(Integer authorizationId, String recordType, boolean update) {
        Authorize authorize = baseMapper.selectById(authorizationId);
        if (authorize == null) {
            throw new RuntimeException("授权记录不存在");
        }

        // 处理修改权限字段(String类型，逗号分隔的recordTypes)
        String updateStr = authorize.getUpdate();
        Set<String> updateSet = new HashSet<>();
        if (updateStr != null && !updateStr.isEmpty()) {
            updateSet.addAll(Arrays.asList(updateStr.split(",")));
        }

        if (update) {
            updateSet.add(recordType);
        } else {
            updateSet.remove(recordType);
        }

        authorize.setUpdate(String.join(",", updateSet));
        baseMapper.updateById(authorize);
    }

    /**
     * 删除记录时移除相关权限
     */
    public void removeRecordPermissions(int recordId) {
        // 获取记录类型
        String recordType = recordMapper.selectRecordtypeByRecordid(recordId);
        log.info("开始移除记录权限: recordId={}, recordType={}", recordId, recordType);
        if (recordType == null) {
            log.warn("记录不存在，无法移除权限: recordId={}", recordId);
            return;
        }

        // 查询所有包含该记录类型权限的授权记录
        QueryWrapper<Authorize> queryWrapper = new QueryWrapper<>();
        queryWrapper.or().apply("FIND_IN_SET({0}, look)", recordType)
                    .or().apply("FIND_IN_SET({0}, `delete`)", recordType)
                    .or().apply("FIND_IN_SET({0}, `update`)", recordType);
        List<Authorize> authorizes = authorizeMapper.selectList(queryWrapper);
        log.info("查询到相关授权记录数量: {}", authorizes.size());

        // 更新每个授权记录，移除该记录类型的权限
        int processedCount = 0;
        for (Authorize authorize : authorizes) {
            updateLookPermission(authorize.getId(), recordType, false);
            updateDeletePermission(authorize.getId(), recordType, false);
            updateUpdatePermission(authorize.getId(), recordType, false);
            processedCount++;
            log.info("已处理授权记录: authorizationId={}", authorize.getId());
        }
        log.info("权限移除完成: 共处理{}条授权记录, recordType={}, recordId={}", processedCount, recordType, recordId);
    }
}


